package me.nibo.bignerdranch.criminalintent;

import android.content.Context;
import android.util.Log;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Crime数据存储类
 *
 * @author nibo
 */
public class CrimeLab {
    private static final String TAG = CrimeLab.class.getSimpleName();
    private static final String FILENAME = "crimes.json";
    private static CrimeLab sCrimeLab;
    private Context mAppContext;
    private List<Crime> mCrimes;
    private CriminalIntentJSONSerializer mSerializer;

    private CrimeLab(Context appContext) {
        mAppContext = appContext;
        mSerializer = new CriminalIntentJSONSerializer(mAppContext, FILENAME);
        try {
            mCrimes = mSerializer.loadCrimes();
            Log.d(TAG, "从文件中加载Crime数据");
        } catch (IOException | JSONException e) {
            Log.e(TAG, "从文件中加载Crime数据异常！", e);
            mCrimes = new ArrayList<>();
        }
    }

    /**
     * 获取CrimeLab实例
     *
     * @param context 应用上下文
     * @return CrimeLab
     */
    public static CrimeLab get(Context context) {
        if (sCrimeLab == null) {
            sCrimeLab = new CrimeLab(context.getApplicationContext());
        }
        return sCrimeLab;
    }

    /**
     * 获取Crime数据列表
     *
     * @return Crime数据列表
     */
    public List<Crime> getmCrimes() {
        return mCrimes;
    }

    /**
     * 根据指定id获取Crime对象
     *
     * @param uuid id
     * @return Crime
     */
    public Crime getmCrimes(UUID uuid) {
        for (Crime c : mCrimes) {
            if (c.getmId().equals(uuid)) {
                return c;
            }
        }
        return null;
    }

    /**
     * 添加Crime
     *
     * @param crime Crime对象
     */
    public void addCrime(Crime crime) {
        mCrimes.add(crime);
    }

    /**
     * 删除Crime
     * @param crime Crime对象
     */
    public void deleteCrime(Crime crime) {
        mCrimes.remove(crime);
    }

    /**
     * 保存Crime数据到文件
     *
     * @return true:成功<br>false:失败
     */
    public boolean saveCrimes() {
        try {
            mSerializer.saveCrimes(mCrimes);
            Log.d(TAG, "保存Crime数据到文件");
            return true;
        } catch (JSONException | IOException e) {
            Log.e(TAG, "保存Crime数据异常！", e);
            return false;
        }
    }
}
